#include "History.h"

#include <stdio.h>

History::History()
	: _semaphore(1)
{

}

History::~History()
{
}

void History::store(Reading r)
{
	_semaphore.wait();
	_data.push_back(r);
	_semaphore.signal();

}

vector<Reading> History::tail(int n, int base)
{
	vector<Reading> v;
	deque<Reading>::iterator p;

	_semaphore.wait();	
	printf("size=%d;base=%i;n=%i;size-n*base=%i\n", _data.size(), base, n, _data.size()-n*base+1);


	if (_data.size() < n)
		p = _data.begin();	
	else
		p = _data.end()-n;

	for( ; p != _data.end(); p+=1 )
	{ 
		v.push_back(*p); 
	}
	_semaphore.signal();	

	return v;
}

void History::print(int n)
{
	deque<Reading>::iterator p;

	_semaphore.wait();
	if (_data.size() < n)
		p = _data.begin();
	else
		p = _data.end()-n;
	

	for( ; p != _data.end(); ++p )
	{ 
		printf("(%i,%i)\n", p->timestamp, p->value); 
	}
	_semaphore.signal();
}

bool History::readFile(string file)
{
	Reading r;
	FILE* pFile = fopen(file.c_str(), "r");

	_data.clear();
	if(pFile)
	{
		while(fscanf(pFile, "%i %i\r", &r.timestamp, &r.value) != EOF)
			_data.push_back(r);
		fclose(pFile);
	}
	return (pFile != 0);
}
